package com.koron.css2.projectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BankBean;
import com.koron.css2.baseConfig.bean.BusinessAbodeBean;
import com.koron.css2.baseConfig.bean.ProjectPayeeBean;
import com.koron.css2.baseConfig.mapper.BankMapper;
import com.koron.css2.baseConfig.mapper.BusinessAbodeMapper;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.baseConfig.mapper.ProjectPayeeMapper;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.newProjectCenter.bean.ProjectReceiptBean;
import com.koron.css2.newProjectCenter.bean.query.ProjectReceiptQueryBean;
import com.koron.css2.newProjectCenter.mapper.ProjectReceiptMapper;
import com.koron.css2.projectCenter.bean.PjConsultBean;
import com.koron.css2.projectCenter.bean.PjInstallBean;
import com.koron.css2.projectCenter.bean.query.PjConsultQueryBean;
import com.koron.css2.projectCenter.dto.*;
import com.koron.css2.projectCenter.mapper.PjConsultMapper;
import com.koron.css2.projectCenter.mapper.PjInstallMapper;
import com.koron.css2.projectCenter.vo.PjInstallDetailVO;
import com.koron.css2.serviceManage.bean.DistrictBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DistrictMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.OrgUserQueryBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 用水安装详情
 * @author 许海宜
 * 2020年4月3日
 */
public class PjInstallQuery implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			//将入参转换为QueryBean
			PjConsultQueryBean queryBean = JsonUtils.objectToPojo(req.getData(), PjConsultQueryBean.class);
			if(StringUtils.isBlank(queryBean.getId())) {
				return MessageBean.create(Constant.NOT_NULL, "主键不能为空。", null);
			}
			
			//查询用水安装
			PjInstallMapper mapper = factory.getMapper(PjInstallMapper.class);
			PjInstallBean pjInstallBean = mapper.selectById(queryBean.getId());
			if (pjInstallBean == null) {
				return MessageBean.create(Constant.NOT_NULL, "用水安装单据不存在。", null);
			}
			
			//查询用水咨询
			PjConsultMapper consultMapper = factory.getMapper(PjConsultMapper.class);
			PjConsultBean pjConsultBean= consultMapper.selectById(pjInstallBean.getConsultId());
			if (pjConsultBean == null) {
				return MessageBean.create(Constant.NOT_NULL, "用水咨询单据不存在。", null);
			}
			
			//查询客户信息
			CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
			CtmInfoBean ctmInfoBean = ctmMapper.getCtmInfoById(pjConsultBean.getUserCtmTempId(), CtmInfoBean.CTMTEMP);
			
			//输出VO组装，按节点拆开
			PjInstallDetailVO detailVO = new PjInstallDetailVO();
			//转单据信息
			CommonUtils.copyPropertiesIgnoreNull(pjInstallBean, detailVO);
			//添加客户信息
			detailVO.setCtmInfo(ctmInfoBean);
			
			//转登记信息
			PjConsultRegisterDto registerDto = new PjConsultRegisterDto();
			CommonUtils.copyPropertiesIgnoreNull(pjConsultBean, registerDto);
			detailVO.setRegister(registerDto);
			
			//转收款信息
			PjInstallChargeDto chargeDto = new PjInstallChargeDto();
			CommonUtils.copyPropertiesIgnoreNull(pjInstallBean, chargeDto);
			
			chargeDto.setPrepayMoney(pjConsultBean.getBudgetMoney());
			chargeDto.setDepositMoney(pjConsultBean.getDepositMoney());
			chargeDto.setBudgetMoney(pjConsultBean.getBudgetMoney()+(pjConsultBean.getDepositMoney()==null?0.0:pjConsultBean.getDepositMoney()));
			detailVO.setCharge(chargeDto);
			//转施工信息
			PjInstallBuildDto buildDto = new PjInstallBuildDto();
			CommonUtils.copyPropertiesIgnoreNull(pjInstallBean, buildDto);
			buildDto.setProjectCharge(pjConsultBean.getProjectCharge());
			detailVO.setBuild(buildDto);
			//转验收信息
			PjInstallCheckDto checkDto = new PjInstallCheckDto();
			CommonUtils.copyPropertiesIgnoreNull(pjInstallBean, checkDto);
			detailVO.setCheck(checkDto);
			//转结算信息
			PjInstallSetmtDto setmtDto = new PjInstallSetmtDto();
			CommonUtils.copyPropertiesIgnoreNull(pjInstallBean, setmtDto);
			//Double Money = setmtDto.getSetmtMoney()==null?0.0:setmtDto.getSetmtMoney()-pjConsultBean.getBudgetMoney();
			//setmtDto.setBackFillMoney(Money);
			//获取收款单合计，作为预缴合计
			ProjectReceiptMapper totalMapper = factory.getMapper(ProjectReceiptMapper.class);
			ProjectReceiptQueryBean receipt = new ProjectReceiptQueryBean();
			receipt.setBillNo(pjInstallBean.getBillNo());
			receipt.setChargeType("9");
			List<ProjectReceiptBean> totalReceipt = totalMapper.listTotal(receipt);
			double prepayMoney = 0;
			if(totalReceipt!=null) {
				prepayMoney = totalReceipt.get(0)==null?0:totalReceipt.get(0).getReceivableMoney();
			}
			
			setmtDto.setPrepayMoney(prepayMoney);
			if("Process-task13".equals(detailVO.getProcessState())) {
				int total = totalMapper.totalCount(pjInstallBean.getId());
				if("2".equals(pjConsultBean.getPrepayType()) && total==1) {
					setmtDto.setSetmtFlag(1);
				}
			}
			detailVO.setSetmt(setmtDto);
			//转退款信息
			PjInstallRefundDto refundDto = new PjInstallRefundDto();
			CommonUtils.copyPropertiesIgnoreNull(pjInstallBean, refundDto);
			detailVO.setRefund(refundDto);
			//数据字典转换
			convert(factory, detailVO, userInfo);
			//判断是否审批节点
			detailVO.setApproveFlag(0);
			if(!StringUtils.isBlank(detailVO.getProcessState()) 
					&& (detailVO.getProcessState().indexOf("Process") >= 0
							|| "CANCEL".equals(detailVO.getProcessState())
							|| "END".equals(detailVO.getProcessState()))) {
				detailVO.setProcessState(detailVO.getProcessState().replace("-approval", ""));
				detailVO.setApproveFlag(1);
			}
			//输出分页结果
			MessageBean<PjInstallDetailVO> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PjInstallDetailVO.class);
			info.setData(detailVO);
			return info;
		} catch (Exception e) {
			logger.error("用水咨询详情查询失败"+e.getMessage(), e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
		}
	}

	/**
	 * 数据字典转换
	 * @param vo
	 */
	private void convert(SessionFactory factory, PjInstallDetailVO vo, UserInfoBean userInfo) {
		//客户信息
		CtmInfoBean ctmInfo = vo.getCtmInfo();
		//用水咨询登记信息
		PjConsultRegisterDto register = vo.getRegister();
		//安装施工
		PjInstallBuildDto builder = vo.getBuild();
		PjInstallCheckDto check = vo.getCheck();
		PjInstallSetmtDto setmt = vo.getSetmt();
		PjInstallRefundDto refund = vo.getRefund();
		//营业所
		if(!StringUtils.isBlank(register.getBusinessAbode())) {
			BusinessAbodeMapper abodeMapper = factory.getMapper(BusinessAbodeMapper.class);
			BusinessAbodeBean abodeName = abodeMapper.findBusinessAbodeById(register.getBusinessAbode());
			register.setBusinessAbodeName(abodeName!=null?abodeName.getAbodeName():"");
		}
		//营业区域
		if(!StringUtils.isBlank(register.getBusinessArea())) {
			BusinessAreaMapper areaMapper = factory.getMapper(BusinessAreaMapper.class);
			register.setBusinessAreaName(areaMapper.findBusinessAreaById(register.getBusinessArea(), userInfo.getCurWaterCode()));
		}
		//行政区域
		if(!StringUtils.isBlank(register.getAdminArea())) {
			DistrictMapper districtMapper = factory.getMapper(DistrictMapper.class);
			DistrictBean adminName = districtMapper.findDistrictById(register.getAdminArea());
			register.setAdminAreaName(adminName!=null?adminName.getName():"");
		}
		//工程类型PPT
		register.setPjTypeName(Tools.getDicNameByCodeAndValue(factory, "PPT", register.getPjType()));
		//紧急程度EGD
		register.setUrgentFlag(Tools.getDicNameByCodeAndValue(factory, "EGD", register.getUrgentFlag()));
		//用水期UWD
		register.setLimitFlagName(Tools.getDicNameByCodeAndValue(factory, "UWD", register.getLimitFlag()));
		//信息来源PIS
		register.setSourceFlagName(Tools.getDicNameByCodeAndValue(factory, "PIS", register.getSourceFlag()));
		//客户类型CTT
		ctmInfo.setCtmType(Tools.getDicNameByCodeAndValue(factory, "CTT", ctmInfo.getCtmType()));
		//证件类型IDT
		ctmInfo.setCertType(Tools.getDicNameByCodeAndValue(factory, "IDT", ctmInfo.getCertType()));
		register.setAgentCertTypeName(Tools.getDicNameByCodeAndValue(factory, "IDT", register.getAgentCertType()));
		//信用等级CDL
		ctmInfo.setCreditLevelName(Tools.getDicNameByCodeAndValue(factory, "CDL", ctmInfo.getCreditLevel()));
		//转化岗位人员名称
		//1.施工人员
		OrgUserMapper omapper = factory.getMapper(OrgUserMapper.class);
		if(builder!=null && !StringUtils.isBlank(builder.getConstGroup())) {
			OrgUserQueryBean orgUserQueryBean = new OrgUserQueryBean();
			orgUserQueryBean.setUserAccounts(Arrays.asList(builder.getConstGroup().split(",")));
			List<OrgUserBean> olist = omapper.selectByAccounts(orgUserQueryBean);
			if(olist!=null && olist.size()>0) {
				List<String> installStaffName = new ArrayList<String>();
				for (int i=0;i<olist.size();i++) {
					installStaffName.add(olist.get(i).getUserName());
				}
				builder.setConstGroupName(String.join(",", installStaffName));
			}
		}
		//工程收款主体
		if(builder.getProjectCharge()  !=null){
			//收款主体
			ProjectPayeeBean bean = new ProjectPayeeBean();
			bean.setId(builder.getProjectCharge());
			ProjectPayeeMapper mapper = factory.getMapper(ProjectPayeeMapper.class);
			ProjectPayeeBean rojectPayeeBean = mapper.query(bean);
			builder.setProjectCharge(rojectPayeeBean!=null?rojectPayeeBean.getSubjectName():"");
		}
		//验收人员
		/*
		if(check != null && !StringUtils.isBlank(check.getCheckStaff())) {
			OrgUserBean user = omapper.selectByAccount(check.getCheckStaff());
			check.setCheckStaffName(user==null?"":user.getUserName());
		*/
		if(!StringUtils.isBlank(check.getCheckStaff())) {
			OrgUserQueryBean orgUserQueryBean = new OrgUserQueryBean();
			orgUserQueryBean.setUserAccounts(Arrays.asList(check.getCheckStaff().split(",")));
			List<OrgUserBean> olist = omapper.selectByAccounts(orgUserQueryBean);
			if(olist!=null && olist.size()>0) {
				List<String> CheckStaffName = new ArrayList<String>();
				for (int i=0;i<olist.size();i++) {
					CheckStaffName.add(olist.get(i).getUserName());
				}
				check.setCheckStaffName(String.join(",", CheckStaffName));
			}
		}
		//结算人员
		if(!StringUtils.isBlank(setmt.getSetmtStaff())) {
			OrgUserBean user = omapper.selectByAccount(setmt.getSetmtStaff());
			setmt.setSetmtStaffName(user==null?"":user.getUserName());
		}
		//开户行
		if(!StringUtils.isBlank(refund.getBankName())){
			BankMapper bankMapper = factory.getMapper(BankMapper.class);
			BankBean bankBean = bankMapper.findBankById(refund.getBankName());
			refund.setBankNameName(bankBean.getBankName());
		}
	}
}
